#!/usr/bin/python3

"""
3. 信息查看程序 /var/www/cgi/monitor9
    1. 检验用户是否登录
    2. 根据是否登录显示相应内容
"""

import os
import json
import time
import subprocess as sub

from lib import session_expire, write_session_data, session_dir


def cpu():
    p = sub.Popen(['uptime'], stdout=sub.PIPE)
    stdout = p.stdout.read().decode()
    p.wait()
    m1, m5, m15 = stdout.replace(',', '').split()[-3:]
    return '1 minute: %s\n5 minutes: %s\n15 minutes: %s\n' % (m1, m5, m15)


def ram():
    p = sub.Popen(['free'], stdout=sub.PIPE)
    stdout = p.stdout.read().decode()
    total, used, free = stdout.splitlines()[1].split()[1:4]
    return 'total: %s\nused: %s\nfree: %s\n' % (total, used, free)


def hd():
    p = sub.Popen(['df', '-h'], stdout=sub.PIPE)
    stdout = p.stdout.read().decode()
    lines = stdout.splitlines()
    root_line = [line for line in lines if line.endswith('/')][0]
    dev, size, used, avail, pct = root_line.split()[:5]
    fmt = 'dev: %s\nsize: %s\nused: %s\navail: %s\npct: %s\n'
    return fmt % (dev, size, used, avail, pct)


def online_user():
    p = sub.Popen(['who'], stdout=sub.PIPE)
    stdout = p.stdout.read().decode()
    return '\nONLINE USERS:\n' + stdout


def get_sid():
    # 获取session的id
    cookies = os.getenv('HTTP_COOKIE', '')
    cookies = dict([x.strip().split('=') for x in cookies.split(';')])
    sid = cookies.get('sessionid')
    return sid


def read_session_data():
    sid = get_sid()
    if not sid:
        raise Exception('no session id')

    # 打开session数据文件
    session_file = os.path.join(session_dir, sid)
    try:
        ifile = open(session_file)
    except FileNotFoundError:
        raise Exception('session file not exists')

    session_data_text = ifile.read()
    session_data = json.loads(session_data_text)
    return session_data


def is_login():
    # 读取session数据，当cookie中没有session的id，
    # 或者session的文件找不到时，都会有异常抛出。
    try:
        session_data = read_session_data()
    except Exception:
        sid = get_sid()
        if sid:
            clear_session(sid)

    expire = session_data['expire']
    now = int(time.time())

    # 如果超时时间expire大于或等于当前时间，就认为已经登录（登录状态继续生效），
    # 否则，就认为没有登录。
    if expire >= now:
        # 未过期
        return True
    else:
        # 已过期，删除session数据
        sid = get_sid()
        if sid:
            clear_session(sid)
        return False


def clear_session(sid):
    session_file = os.path.join(session_dir, sid)
    try:
        os.remove(session_file)
    except FileNotFoundError:
        ...


def update_session_expire():
    # 更新session数据中的超时时间
    session_data = read_session_data()
    now = int(time.time())
    session_data['expire'] = now + session_expire
    sid = get_sid()
    write_session_data(sid, json.dumps(session_data))


if __name__ == '__main__':
    qs = os.getenv('QUERY_STRING')
    if 't=cpu' in qs:
        text = cpu()
    elif 't=ram' in qs:
        text = ram()
    elif 't=hd' in qs:
        text = hd()
    else:
        text1 = cpu()
        text2 = ram()
        text3 = hd()
        text = 'CPU:\n%s\nRAM:\n%s\nHD:\n%s' % (text1, text2, text3)

    # 检查是否登录，如果已经登录，就显示在线用户信息
    if is_login():
        online_user_info = online_user()
        update_session_expire()
        text += online_user_info

    print('Content-Type: text/plain\n\n', end='')
    print(text)
